package com.yjf.ljr.view;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.yjf.ljr.R;
import com.yjf.ljr.activity.ConfirmationTransferActivity;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.connection.IjConnect;
import com.yjf.ljr.dataclass.AppinvestDataClass;
import com.yjf.ljr.dataclass.SendSmsCodeDataClass;
import com.yjf.ljr.dataclass.TransferSubmitDataClass;
import com.yjf.ljr.dataclass.VerifySmsCodeDataClass;
import com.yjf.ljr.parser.RequestBuilder;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;
import com.yjf.ljr.view.TransferPubDialog.Builder;
import com.yjf.ljr.view.TransferPubDialog.Builder.SendSmsCodeTask;
import com.yjf.ljr.view.TransferPubDialog.Builder.TransfersInvestSubTask;

public class TransferDialog extends Dialog {

	public TransferDialog(Context context) {
		super(context);

	}

	public TransferDialog(Context context, int theme) {
		super(context, theme);
	}

	public static class Builder {
		private Context context;
		private String title;
		private String paypassUrl;
		// private CookieManager mCookieManager;
		private String token;
		private String tradeId;// 当前项目的tradeID
		private String demandId;// 项目ID

		// add red packet and experience amount
		private String giftMoney;// 红包
		private String experienceAmount;// 体验金

//		private String positiveButtonText;
//		private String negativeButtonText;
//		private View contentView;
//		private ProgressBar mProgressBar;
//		private LinearLayout mLayoutInvestPayBlank;
//		private WebView mwebView;
//		private LinearLayout mLlTitleyjfPaypassUrl;
//		private DialogInterface.OnClickListener positiveButtonClickListener;
//		private DialogInterface.OnClickListener negativeButtonClickListener;
		private boolean resultFlag = false;
		private CookieManager mCookieManager;
		private String paytk;// 支付令牌
		private String tradeDetailId;// 查询Id
		private String amount;// 转让金额
		
		
		private ProgressBar mProgressBar;
		private TextView etCommonPhone;
		private EditText etVerifyCode;
		private Button btnGetVerifyCode;
		private Button sure_btn;
		private Button cancel_btn;
		private View contentView;
		private String mobile;
		
		private View.OnClickListener listener;

		private Handler mHandler = new Handler() {
			public void handleMessage(Message msg) {
				int time = (Integer) msg.obj;
				btnGetVerifyCode.setText(String.format("%02d秒", time));
				if (time-- > 0) {
					mHandler.sendMessageDelayed(mHandler.obtainMessage(0, time), 1000);
				} else {
					btnGetVerifyCode.setBackgroundResource(R.drawable.verification_selector);
					btnGetVerifyCode.setClickable(true);
					btnGetVerifyCode.setText("获取");
				}
			}
		};
		

		private boolean showProgress = false;

		public Builder(Context context) {
			this.context = context;

		}

		public Builder setTradeDetailId(int tradeDetailId) {
			this.tradeDetailId = (String) context.getText(tradeDetailId);
			return this;
		}

		public Builder setTradeDetailId(String tradeDetailId) {
			this.tradeDetailId = tradeDetailId;
			return this;
		}

		public Builder setPaypassUrl(String paypassUrl) {
			this.paypassUrl = paypassUrl;
			resultFlag = false;
			return this;
		}

		/**
		 * Set the Dialog message from resource
		 * 
		 * @param title
		 * @return
		 */
		public Builder setPaypassUrl(int paypassUrl) {
			this.paypassUrl = (String) context.getText(paypassUrl);
			return this;
		}

		public Builder setAmount(String amount) {
			this.amount = amount;
			return this;
		}

		public Builder setAmount(int amount) {
			this.amount = (String) context.getText(amount);
			return this;
		}

		public Builder setToken(String token) {
			this.token = token;

			return this;
		}

		public Builder setToken(int token) {
			this.token = (String) context.getText(token);
			return this;
		}

		public Builder setTradeId(String tradeId) {
			this.tradeId = tradeId;

			return this;
		}

		public Builder setTradeId(int tradeId) {
			this.tradeId = (String) context.getText(tradeId);
			return this;
		}

		public Builder setDemandId(String demandId) {
			this.demandId = demandId;

			return this;
		}

		public Builder setDemandId(int demandId) {
			this.demandId = (String) context.getText(demandId);
			return this;
		}

		/**
		 * set red packet amount
		 * 
		 * @param giftMoney
		 * @return
		 */
		public Builder setGiftMoney(String giftMoney) {
			this.giftMoney = giftMoney;
			return this;
		}

		/**
		 * set experience amount
		 * 
		 * @param experienceAmount
		 * @return
		 */
		public Builder setExperienceAmount(String experienceAmount) {
			this.experienceAmount = experienceAmount;
			return this;
		}

		/**
		 * Set the Dialog title from resource
		 * 
		 * @param title
		 * @return
		 */
		public Builder setTitle(int title) {
			this.title = (String) context.getText(title);
			return this;
		}

		/**
		 * Set the Dialog title from String
		 * 
		 * @param title
		 * @return
		 */

		public Builder setTitle(String title) {
			this.title = title;
			return this;
		}

		public Builder setContentView(View v) {
			this.contentView = v;
			return this;
		}
		
		public Builder setmobile(String mobile) {
			this.mobile = mobile;
			return this;
		}

		String cookieString;

		@SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
		public TransferDialog create() {
			showProgress = false;
			/***************************/
			if (Build.VERSION.SDK_INT >= 11) {
				StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
						.detectNetwork().penaltyLog().build());
				StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
						.detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
			}

			/***************************/

			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			// instantiate the dialog with the custom Theme
			final TransferDialog dialog = new TransferDialog(context, R.style.Dialog);
			View layout = inflater.inflate(R.layout.dialog_invest, null);
			dialog.addContentView(layout, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
			
			mProgressBar = (ProgressBar) layout.findViewById(R.id.appInvestprogressBar);
			etCommonPhone = (TextView) layout.findViewById(R.id.etCommonPhone);
			etVerifyCode = (EditText) layout.findViewById(R.id.etVerifyCode);
			btnGetVerifyCode = (Button) layout.findViewById(R.id.btnGetVerifyCode);
			sure_btn = (Button) layout.findViewById(R.id.sure_btn);
			cancel_btn = (Button) layout.findViewById(R.id.cancel_btn);			
			etCommonPhone.setText(mobile);
			listener = new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					switch(v.getId()) {
					case R.id.btnGetVerifyCode:
						new SendSmsCodeTask(etCommonPhone.getText().toString().trim()).execute();

						btnGetVerifyCode.setBackgroundResource(R.drawable.shape_btn_gray_bg);
						btnGetVerifyCode.setClickable(false);
						mHandler.sendMessageDelayed(mHandler.obtainMessage(0, 60), 0);
						break;
					case R.id.sure_btn:
						String code = etVerifyCode.getText().toString().trim();
						if(TextUtils.isEmpty(code)) {
							Toast.makeText(context, "请输入验证码！", Toast.LENGTH_SHORT).show();
							return;
						}
						new VerifySmsCodeTask(etCommonPhone.getText().toString().trim(),code, amount, tradeDetailId, dialog).execute();
						break;
					case R.id.cancel_btn:
						if(dialog != null && dialog.isShowing()) {
							dialog.dismiss();
						}
						break;
					}
					
				}
			};
			
			btnGetVerifyCode.setOnClickListener(listener);
			sure_btn.setOnClickListener(listener);
			cancel_btn.setOnClickListener(listener);
			dialog.setContentView(layout);
			return dialog;
		}

		class TransferSubmitTask extends AsyncTask<Void, Void, Void> {

			private TransferDialog dialog;
			private String code;
			private String amount;
			private String tradeDetailId;

			private String mFailStr;
			private TransferSubmitDataClass dc = new TransferSubmitDataClass();

			public TransferSubmitTask(String code, String amount, String tradeDetailId, TransferDialog dialog) {

				this.dialog = dialog;
				this.code = code;
				this.amount = amount;
				this.tradeDetailId = tradeDetailId;
			}
	
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				mProgressBar.setVisibility(View.VISIBLE);
			}

			@Override
			protected Void doInBackground(Void... params) {
				RequestObject requestObject = new RequestObject();
				requestObject.method = "transferSubmit";
				requestObject.map.put("tradeDetailId", tradeDetailId);
				requestObject.map.put("amount", amount);
				requestObject.map.put("code", code);
				// add red packet and experience amount

				String requrestUrl = RequestBuilder.build(requestObject);
				try {
					IjConnect.doRequest(requrestUrl, dc);

					if (dc.code == null) {
						mFailStr = "获取数据异常，请稍后重试";
					} else if (!dc.code.equals(CommonData.RESULT_SUCCESS)) {
						mFailStr = dc.msg;
					}
				} catch (Exception e) {
					mFailStr = "获取数据异常，请稍后重试";
					e.printStackTrace();
				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				mProgressBar.setVisibility(View.GONE);
				if (!(TextUtils.isEmpty(mFailStr))) {// fail
					Toast.makeText(context, mFailStr, Toast.LENGTH_LONG).show();
					dialog.dismiss();
				} else {// success
					Toast.makeText(context, dc.msg, Toast.LENGTH_LONG).show();
					dialog.dismiss();
					ConfirmationTransferActivity.mDialogTransfering.show();

				}
			}

		}
		
		class SendSmsCodeTask extends AsyncTask<Void, Void, String> {

			private String mobile;// 电话号码
			private SendSmsCodeDataClass dc = new SendSmsCodeDataClass();

			public SendSmsCodeTask(String mobile) {
				this.mobile = mobile;
			}
			
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				mProgressBar.setVisibility(View.VISIBLE);
			}

			@Override
			protected String doInBackground(Void... arg0) {
				RequestObject requestObject = new RequestObject();
				requestObject.method = "sendSmsCode";
				requestObject.map.put("mobile", mobile);
				requestObject.map.put("business", "invest");
				String failStr = "";
				String requrestUrl = RequestBuilder.build(requestObject);
				try {
					IjConnect.doRequest(requrestUrl, dc);
					if (dc.code == null) {
						failStr = "获取数据异常，请稍后重试";
					} else if (!dc.code.equals(CommonData.RESULT_SUCCESS)) {
						failStr = dc.msg;
					}
				} catch (Exception e) {
					failStr = "获取数据异常，请稍后重试";
					e.printStackTrace();
				}
				return failStr;
			}

			@Override
			protected void onPostExecute(String result) {
				mProgressBar.setVisibility(View.GONE);
				if (!TextUtils.isEmpty(result)) {
					Toast.makeText(context, result, Toast.LENGTH_LONG).show();
				} else {
					if ("1".equals(dc.code)) {
						Toast.makeText(context, "验证码已发送，请注意查收", Toast.LENGTH_LONG).show();
					}
				}
			}
		}

		/******** 验证短信验证码是否正确 ******/
		class VerifySmsCodeTask extends AsyncTask<Void, Void, String> {
			private String mobile;// 手机号码
			private String code;// 验证码
			private VerifySmsCodeDataClass dc = new VerifySmsCodeDataClass();
			private String amount;
			private String tradeDetailId;
			private TransferDialog dialog;

			public VerifySmsCodeTask(String mobile, String code, String amount, String tradeDetailId, TransferDialog dialog) {
				this.mobile = mobile;
				this.code = code;
				this.amount = amount;
				this.tradeDetailId = tradeDetailId;
				this.dialog = dialog;
			}

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				mProgressBar.setVisibility(View.VISIBLE);
			}

			@Override
			protected String doInBackground(Void... params) {
				RequestObject mObject = new RequestObject();
				mObject.method = "verifySmsCode";
				mObject.map.put("mobile", mobile);
				mObject.map.put("code", code);
				mObject.map.put("business", "invest");//这个需要修改，现在还没这个状态的字段
				String failStr = "";
				String requrestUrl = RequestBuilder.build(mObject);
				try {
					IjConnect.doRequest(requrestUrl, dc);
					if (dc.code == null) {
						failStr = "获取数据异常，请稍后重试";
					} else if (!dc.code.equals(CommonData.RESULT_SUCCESS)) {
						failStr = dc.msg;
					}
				} catch (Exception e) {
					failStr = "获取数据异常，请稍后重试";
					e.printStackTrace();
				}
				return failStr;
			}

			@Override
			protected void onPostExecute(String result) {
				mProgressBar.setVisibility(View.GONE);
				super.onPostExecute(result);
				if (!TextUtils.isEmpty(result)) {// fail
					Toast.makeText(context, result, Toast.LENGTH_SHORT).show();					
				} else {// success
					new TransferSubmitTask(code, amount, tradeDetailId, dialog).execute();
				}			
			}
		}
		
	}

}
